﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Aioms.Common;
using Aioms.Dtos;
using Aioms.Model;
using Aioms.Models;
using Furion;
using Furion.DataEncryption;
using Furion.DynamicApiController;
using Furion.LinqBuilder;
using Furion.UnifyResult;
using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Excel;
using Mapster;
using Masuit.Tools;
using Masuit.Tools.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;
using SqlSugar.Extensions;
using StackExchange.Profiling.Internal;
using Ubiety.Dns.Core.Records;

namespace Aioms.Controllers
{
    /// <summary>
    /// 报表
    /// </summary>
    [DynamicApiController]
    public class ReportFormController
    {
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public ReportFormController(ISqlSugarClient sqlSugarClient)
        {
            this.db = sqlSugarClient;
        }

        /// <summary>
        /// 计划工单列表
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="content"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostTaskplanworkorderlist([FromForm] long eid, [FromForm] string content, [FromForm] int pageIndex = 1, [FromForm] int pageSize = 10)
        {
            RefAsync<int> total = 0;
            List<TpWorkOrder> tpWorkOrders = await db.Queryable<TpWorkOrder>()
                .Mapper(async wo => {
                    if (!string.IsNullOrEmpty(wo.Epids))
                    {
                        List<string> realnames = await db.Queryable<Employee>().Where($"FIND_IN_SET(id, '{wo.Epids}')").Select(ep => ep.Realname).ToListAsync();
                        wo.EpRealnames = string.Join(",", realnames.ToArray());
                    }
                })
                .Mapper(wo => {
                    if (wo.Type.Equals("巡检工单"))
                    {
                        XunJianPlan xjp = wo.TaskInfo.ToObject<XunJianPlan>();
                        wo.ChildrenCount = (int)(xjp?.XunJianDians?.Count);
                    }
                    else if (wo.Type.Equals("点检工单"))
                    {
                        DianJianPlan djp = wo.TaskInfo.ToObject<DianJianPlan>();
                        wo.ChildrenCount = djp == null ? 0 : djp.DianJianDevices.Count;
                    }
                    else if (wo.Type.Equals("保养工单"))
                    {
                        BaoYangPlan byp = wo.TaskInfo.ToObject<BaoYangPlan>();
                        wo.ChildrenCount = (int)(byp?.BaoYangDevices?.Count);
                    }
                    else
                    {
                    }
                })
                .Where(wo => wo.Eid == eid)
                .Where(wo => wo.Status == "已完成")
                .WhereIF(!string.IsNullOrEmpty(content), wo => wo.Name.Contains(content))
                .OrderBy(wo => wo.Id, OrderByType.Desc)
                .ToPageListAsync(pageIndex, pageSize, total);

            UnifyContext.Fill(new { Total = total });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = tpWorkOrders,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 计划工单列表导出
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostTaskplanworkorderlistexport([FromForm] long eid, [FromForm] string content)
        {
            RefAsync<int> total = 0;
            List<TpWorkOrder> workorders = await db.Queryable<TpWorkOrder>()
                .Mapper(async wo =>
                {
                    if (!string.IsNullOrEmpty(wo.Epids))
                    {
                        List<string> realnames = await db.Queryable<Employee>().Where($"FIND_IN_SET(id, '{wo.Epids}')").Select(ep => ep.Realname).ToListAsync();
                        wo.EpRealnames = string.Join(",", realnames.ToArray());
                    }
                })
                .Where(wo => wo.Eid == eid)
                .Where(wo => wo.Status == "已完成")
                .WhereIF(!string.IsNullOrEmpty(content), wo => wo.Name.Contains(content))
                .OrderBy(wo => wo.Id, OrderByType.Desc)
                .ToListAsync();

            IExporter exporter = new ExcelExporter();
            await exporter.Export(@"wwwroot/download/baoxiu/计划工单列表.xlsx", workorders.Adapt<List<TaskPlanGongDanListExportDto>>());

            JObject data = new();
            data.Add("url", $"http://{App.HttpContext.Request.Host.Value}/download/baoxiu/计划工单列表.xlsx");

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 计划工单列表-查看
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="woid"></param>
        /// <param name="ilid"></param>
        /// <param name="ipid"></param>
        /// <param name="dvid"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostTaskplanworkordershow([FromForm] long eid, [FromForm] long woid, [FromForm] long ilid, [FromForm] long ipid, [FromForm] long dvid)
        {
            //List<InspectionPointOptionResult> inspectionpointoptionresults = null;
            //List<DeviceStandardResult> devicestandardresults = null;

            dynamic data = null;

            if (ipid > 0)
            {
                //List<long> ipids = await db.Queryable<InspectionPoint>().Where(ip => ip.Eid == eid && ip.Ilid == ilid).Select(ip => ip.Id).ToListAsync();
                data = await db.Queryable<InspectionPointOptionResult>()
                    .Where(ipor => ipor.Eid == eid)
                    .Where(ipor => ipor.Woid == woid)
                    .Where(ipor => ipor.Ilid == ilid)
                    .Where(ipor => ipor.Ipid == ipid)
                    .ToListAsync();
                // 巡检点下的巡检设备
                if (dvid > 0) {
                    TpWorkOrder workOrder = await db.Queryable<TpWorkOrder>().InSingleAsync(woid);
                    XunJianPlan xunJianPlan = workOrder.TaskInfo.ToObject<XunJianPlan>();
                    XunJianDevice xunJianDevice = xunJianPlan.XunJianDians.Where(xjd => xjd.Id == ipid).Select(xjd => xjd.XunJianDevices.Find(xjdv => xjdv.Id == dvid)).FirstOrDefault();

                    data = await db.Queryable<DeviceStandardResult>()
                    .Where(dsr => dsr.Eid == eid)
                    .Where(dsr => dsr.Woid == woid)
                    .Where(dsr => dsr.Dvid == xunJianDevice.Id)
                    .ToListAsync();
                }
            }
            else
            {
                data = await db.Queryable<DeviceStandardResult>()
                    .Where(dsr => dsr.Eid == eid)
                    .Where(dsr => dsr.Woid == woid)
                    .Where(dsr => dsr.Dvid == dvid)
                    .ToListAsync();
            }

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 计划工单列表-查看-导出
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="woid"></param>
        /// <param name="ipid"></param>
        /// <param name="dvid"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostTaskplanworkordershowexport([FromForm] long eid, [FromForm] long woid, [FromForm] long ipid, [FromForm] long dvid, [FromForm] string excelname)
        {
            List<InspectionPointOptionResult> inspectionpointoptionresults = null;
            List<DeviceStandardResult> devicestandardresults = null;

            if (ipid > 0)
            {
                //List<long> ipids = await db.Queryable<InspectionPoint>().Where(ip => ip.Eid == eid && ip.Ilid == ilid).Select(ip => ip.Id).ToListAsync();
                inspectionpointoptionresults = await db.Queryable<InspectionPointOptionResult>()
                    .Where(ipor => ipor.Eid == eid)
                    .Where(ipor => ipor.Woid == woid)
                    .Where(ipor => ipor.Ipid == ipid)
                    .ToListAsync();
            }
            else
            {
                devicestandardresults = await db.Queryable<DeviceStandardResult>()
                    .Where(dsr => dsr.Eid == eid)
                    .Where(dsr => dsr.Woid == woid)
                    .Where(dsr => dsr.Dvid == dvid)
                    .ToListAsync();
            }



            //IExporter exporter = new ExcelExporter();
            //await exporter.Export($"wwwroot/download/baoxiu/{excelname}.xlsx", workorders.Adapt<List<TaskPlanGongDanListExportDto>>());

            JObject data = new();
            data.Add("url", $"http://{App.HttpContext.Request.Host.Value}/download/baoxiu/{excelname}.xlsx");

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 维修工单列表
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="content"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostNoticerepairworkorderlist([FromForm] long eid, [FromForm] string content, [FromForm] int pageIndex = 1, [FromForm] int pageSize = 10)
        {
            RefAsync<int> total = 0;
            List<NrWorkOrder> nrWorkOrders = await db.Queryable<NrWorkOrder>()
                .Mapper(async wo => {
                    if (!string.IsNullOrEmpty(wo.Epids))
                    {
                        List<string> realnames = await db.Queryable<Employee>().Where($"FIND_IN_SET(id, '{wo.Epids}')").Select(ep => ep.Realname).ToListAsync();
                        wo.EpRealnames = string.Join(",", realnames.ToArray());
                    }
                })
                .Mapper(wo => wo.NoticeRepair, wo => wo.NpId, wo =>wo.NoticeRepair.Id)
                .Where(wo => wo.Eid == eid)
                .WhereIF(!string.IsNullOrEmpty(content), wo => wo.Name.Contains(content) || wo.Dvname.Contains(content))
                .OrderBy(wo => wo.Id, OrderByType.Desc)
                .ToPageListAsync(pageIndex, pageSize, total);

            UnifyContext.Fill(new { Total = total });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = nrWorkOrders,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 维修工单列表导出
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostNoticerepairworkorderlistexport([FromForm] long eid, [FromForm] string content)
        {
            List<NrWorkOrder> nrWorkOrders = await db.Queryable<NrWorkOrder>()
                .Mapper(async wo =>
                {
                    if (!string.IsNullOrEmpty(wo.Epids))
                    {
                        List<string> realnames = await db.Queryable<Employee>().Where($"FIND_IN_SET(id, '{wo.Epids}')").Select(ep => ep.Realname).ToListAsync();
                        wo.EpRealnames = string.Join(",", realnames.ToArray());
                    }
                })
                .Mapper(wo => wo.NoticeRepair, wo => wo.NpId, wo => wo.NoticeRepair.Id)
                .Where(wo => wo.Eid == eid)
                .WhereIF(!string.IsNullOrEmpty(content), wo => wo.Name.Contains(content) || wo.Dvname.Contains(content))
                .OrderBy(wo => wo.Id, OrderByType.Desc)
                .ToListAsync();

            IExporter exporter = new ExcelExporter();
            await exporter.Export(@"wwwroot/download/baoxiu/维修工单列表.xlsx", nrWorkOrders.Adapt<List<WeiXiuGongDanListExportDto>>());

            JObject data = new();
            data.Add("url", $"http://{App.HttpContext.Request.Host.Value}/download/baoxiu/维修工单列表.xlsx");

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 维修工单列表查看
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="npid"></param>
        /// <param name="dvid"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostNoticerepairworkordershow([FromForm] long eid, [FromForm] long npid, [FromForm] long dvid)
        {
            List<NoticeRepairResult> noticerepairresults = null;


            noticerepairresults = await db.Queryable<NoticeRepairResult>()
                .Where(nrr => nrr.Eid == eid)
                .Where(nrr => nrr.NpId == npid)
                .Where(nrr => nrr.Dvid == dvid)
                .ToListAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = noticerepairresults,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }


        /*public async Task<IActionResult> PostShebeiguzhangfashenglv([FromForm] long eid, [FromForm] string rt)
        {
            // 设备总数
            int device_count = await db.Queryable<Device>().Where(d => d.Eid == eid).Where(d => d.IsDel == 0).CountAsync();

            if (device_count == 0)
            {
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = -1,
                    Succeeded = false,
                    Data = null,
                    Errors = null,
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }

            Dictionary<string, double> data = new();
            // 计算时间范围段
            DateTime begintime = DateTime.Now;
            DateTime endtime = DateTime.Now;
            DateTime ct = DateTime.Now;
            if (rt.Equals("本周"))
            {
                begintime = ct.AddDays(1 - (ct.DayOfWeek == DayOfWeek.Sunday ? 7 : int.Parse(ct.DayOfWeek.ToString("d")))); // 本周一
                endtime = begintime.AddDays(6); // 本周日
                for (int i = 0; i < 7; i++)
                {
                    // 本周当前时间
                    DateTime select_time = begintime.AddDays(i);
                    // 今天设备故障数
                    int trouble_device_count = await db.Queryable<NoticeRepair>().Where(nr => nr.Eid == eid).Where(nr => nr.TroubleTime.Date == select_time.Date).CountAsync();
                    data.Add(select_time.ToString("yyyy-MM-dd"), (double)trouble_device_count / device_count * 100);
                }
            }

            if (rt.Equals("本月"))
            {
                begintime = ct.AddDays(1 - ct.Day);  //本月月初
                endtime = begintime.AddMonths(1).AddDays(-1);  //本月月末
                for (int i = 0; i < endtime.Day; i++)
                {
                    // 本月当前时间
                    DateTime select_time = begintime.AddDays(i);
                    // 今天设备故障数
                    int trouble_device_count = await db.Queryable<NoticeRepair>().Where(nr => nr.Eid == eid).Where(nr => nr.TroubleTime.Date == select_time.Date).GroupBy(nr => nr.Dvid).CountAsync();
                    data.Add(select_time.ToString("yyyy-MM-dd"), (double)trouble_device_count / device_count * 100);
                }
            }

            if (rt.Equals("本年"))
            {
                begintime = new DateTime(ct.Year, 1, 1);  //本年年初
                for (int i = 0; i < 12; i++)
                {
                    // 本月开始时间和结束时间
                    DateTime select_begin_time = begintime.AddMonths(i);
                    DateTime select_end_time = begintime.AddMonths(i + 1);
                    // 今天设备故障数
                    int trouble_device_count = await db.Queryable<NoticeRepair>().Where(nr => nr.Eid == eid).Where(nr => nr.TroubleTime.Date >= select_begin_time.Date && nr.TroubleTime.Date < select_end_time.Date).GroupBy(nr => nr.Dvid).CountAsync();
                    data.Add($"{i + 1}月", (double)trouble_device_count / device_count * 100);
                }
            }

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }*/

        /// <summary>
        /// 设备故障发生次数
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="rt"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostShebeiguzhangfashengcishu([FromForm] long eid, [FromForm] string rt)
        {
            Dictionary<string, int> data = new();
            // 计算时间范围段
            DateTime begintime = DateTime.Now;
            DateTime endtime = DateTime.Now;
            DateTime ct = DateTime.Now;
            if (rt.Equals("本周"))
            {
                begintime = ct.AddDays(1 - (ct.DayOfWeek == DayOfWeek.Sunday ? 7 : int.Parse(ct.DayOfWeek.ToString("d")))); // 本周一
                endtime = begintime.AddDays(6); // 本周日
                for (int i = 0; i < 7; i++)
                {
                    // 本周当前时间
                    DateTime select_time = begintime.AddDays(i);
                    // 今天设备故障数
                    int total = await db.Queryable<NoticeRepair>().Where(nr => nr.Eid == eid).Where(np => np.IsDel == 0).Where(np => np.TroubleTime.Date == select_time.Date).CountAsync();
                    data.Add(select_time.ToString("yyyy-MM-dd"), total);
                }
            }

            if (rt.Equals("本月"))
            {
                begintime = ct.AddDays(1 - ct.Day);  //本月月初
                endtime = begintime.AddMonths(1).AddDays(-1);  //本月月末
                for (int i = 0; i < endtime.Day; i++)
                {
                    // 本月当前时间
                    DateTime select_time = begintime.AddDays(i);
                    // 今天设备故障数
                    int total = await db.Queryable<NoticeRepair>().Where(nr => nr.Eid == eid).Where(np => np.IsDel == 0).Where(np => np.TroubleTime.Date == select_time.Date).CountAsync();
                    data.Add(select_time.ToString("yyyy-MM-dd"), total);
                }
            }

            if (rt.Equals("本年"))
            {
                begintime = new DateTime(ct.Year, 1, 1);  //本年年初
                for (int i = 0; i < 12; i++)
                {
                    // 本月开始时间和结束时间
                    DateTime select_begin_time = begintime.AddMonths(i);
                    DateTime select_end_time = begintime.AddMonths(i + 1);
                    // 今天设备故障数
                    int total = await db.Queryable<NoticeRepair>().Where(nr => nr.Eid == eid).Where(np => np.IsDel == 0).Where(nr => nr.TroubleTime.Date >= select_begin_time.Date && nr.TroubleTime.Date < select_end_time.Date).CountAsync();
                    data.Add($"{i + 1}月", total);
                }
            }

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }


        /*public async Task<IActionResult> PostShebeichangshangguzhangfashenglv([FromForm] long eid, [FromForm] string rt)
        {
            // 设备总数
            Dictionary<string, string> providerandids = db.Queryable<Device>()
                .Where(d => d.Eid == eid && !SqlFunc.IsNullOrEmpty(d.Manufacturer)).GroupBy(d => d.Manufacturer)
                .Where(d => d.IsDel == 0)
                .Select<KeyValuePair<string, string>>("manufacturer, GROUP_CONCAT(id) as ids").ToList().ToDictionary(it => it.Key, it => it.Value);

            if (providerandids == null)
            {
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = -1,
                    Succeeded = false,
                    Data = null,
                    Errors = null,
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }

            Dictionary<string, double> data = new();
            // 计算时间范围段
            DateTime begintime = DateTime.Now;
            DateTime endtime = DateTime.Now;
            DateTime ct = DateTime.Now;
            if (rt.Equals("本周"))
            {
                begintime = ct.AddDays(1 - (ct.DayOfWeek == DayOfWeek.Sunday ? 7 : int.Parse(ct.DayOfWeek.ToString("d")))); // 本周一
                endtime = begintime.AddDays(6); // 本周日
                // 今天厂商设备故障数
                foreach ((string provider, string ids) in providerandids)
                {
                    int trouble_device_count = await db.Queryable<NoticeRepair>().Where(nr => nr.Eid == eid)
                        .Where(nr => nr.TroubleTime.Date >= begintime.Date && nr.TroubleTime.Date < endtime.Date)
                        .Where($"FIND_IN_SET(dvid, '{ids}')")
                        .GroupBy(nr => nr.Dvid)
                        .Select(nr => SqlFunc.AggregateSum(nr.Id))
                        .CountAsync();
                    data.Add(provider, (double)trouble_device_count / ids.Split(",").Length * 100);
                }
            }

            if (rt.Equals("本月"))
            {
                begintime = ct.AddDays(1 - ct.Day);  //本月月初
                endtime = begintime.AddMonths(1).AddDays(-1);  //本月月末
                // 今天厂商设备故障数
                foreach ((string provider, string ids) in providerandids)
                {
                    int trouble_device_count = await db.Queryable<NoticeRepair>().Where(nr => nr.Eid == eid)
                        .Where(nr => nr.TroubleTime.Date >= begintime.Date && nr.TroubleTime.Date < endtime.Date)
                        .Where($"FIND_IN_SET(dvid, '{ids}')")
                        .GroupBy(nr => nr.Dvid)
                        .Select(nr => SqlFunc.AggregateSum(nr.Id))
                        .CountAsync();
                    data.Add(provider, (double)trouble_device_count / ids.Split(",").Length * 100);
                }
            }

            if (rt.Equals("本年"))
            {
                begintime = new DateTime(ct.Year, 1, 1);  //本年年初
                endtime = new DateTime(ct.Year, 12, 31);  //本年年末
                // 今天厂商设备故障数
                foreach ((string provider, string ids) in providerandids)
                {
                    int trouble_device_count = await db.Queryable<NoticeRepair>().Where(nr => nr.Eid == eid)
                        .Where(nr => nr.TroubleTime.Date >= begintime.Date && nr.TroubleTime.Date < endtime.Date)
                        .Where($"FIND_IN_SET(dvid, '{ids}')")
                        .GroupBy(nr => nr.Dvid)
                        .Select(nr => SqlFunc.AggregateSum(nr.Id))
                        .CountAsync();
                    data.Add(provider, (double)trouble_device_count / ids.Split(",").Length * 100);
                }
            }

            //data = (from od in data orderby od.Value descending select od).Take(5);
            data = data.OrderByDescending(pair => pair.Value).Take(5).ToDictionary(pair => pair.Key, pair => pair.Value);

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }*/

        /// <summary>
        /// 设备生产厂家故障发生次数
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="rt"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostShebeichangshangguzhangfashengcishu([FromForm] long eid, [FromForm] string rt)
        {
            Dictionary<string, int> data = new();
            // 计算时间范围段
            DateTime begintime = DateTime.Now;
            DateTime endtime = DateTime.Now;
            DateTime ct = DateTime.Now;
            if (rt.Equals("本周"))
            {
                begintime = ct.AddDays(1 - (ct.DayOfWeek == DayOfWeek.Sunday ? 7 : int.Parse(ct.DayOfWeek.ToString("d")))); // 本周一
                endtime = begintime.AddDays(6); // 本周日
                                                // 本周厂商设备故障数
                var noticeRepairs = await db.Queryable<NoticeRepair>()
                .Where(nr => nr.Eid == eid)
                .Where(nr => nr.IsDel == 0)
                    .Where(nr => nr.TroubleTime.Date >= begintime.Date && nr.TroubleTime.Date <= endtime.Date)
                    .GroupBy(nr => nr.Manufacturer)
                    .Select(nr => new { Manufacturer = nr.Manufacturer, Total = SqlFunc.AggregateCount(nr.Id) })
                    .OrderBy("total desc")
                    .Take(5)
                    .ToListAsync();
                noticeRepairs.ForEach(nr => data.Add(nr.Manufacturer, nr.Total));
            }

            if (rt.Equals("本月"))
            {
                begintime = ct.AddDays(1 - ct.Day);  //本月月初
                endtime = begintime.AddMonths(1).AddDays(-1);  //本月月末
                // 厂商设备故障数
                var noticeRepairs = await db.Queryable<NoticeRepair>()
                .Where(nr => nr.Eid == eid)
                .Where(nr => nr.IsDel == 0)
                    .Where(nr => nr.TroubleTime.Date >= begintime.Date && nr.TroubleTime.Date <= endtime.Date)
                    .GroupBy(nr => nr.Manufacturer)
                    .Select(nr => new { Manufacturer = nr.Manufacturer, Total = SqlFunc.AggregateCount(nr.Id) })
                    .OrderBy("total desc")
                    .Take(5)
                    .ToListAsync();
                noticeRepairs.ForEach(nr => data.Add(nr.Manufacturer, nr.Total));
            }

            if (rt.Equals("本年"))
            {
                begintime = new DateTime(ct.Year, 1, 1);  //本年年初
                endtime = new DateTime(ct.Year, 12, 31);  //本年年末
                // 厂商设备故障数
                var noticeRepairs = await db.Queryable<NoticeRepair>()
                .Where(nr => nr.Eid == eid)
                .Where(nr => nr.IsDel == 0)
                    .Where(nr => nr.TroubleTime.Date >= begintime.Date && nr.TroubleTime.Date <= endtime.Date)
                    .GroupBy(nr => nr.Manufacturer)
                    .Select(nr => new { Manufacturer = nr.Manufacturer, Total = SqlFunc.AggregateCount(nr.Id) })
                    .OrderBy("total desc")
                    .Take(5)
                    .ToListAsync();
                noticeRepairs.ForEach(nr => data.Add(nr.Manufacturer, nr.Total));
            }

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /*public async Task<IActionResult> PostShebeiguzhangcishu([FromForm] long eid, [FromForm] string rt)
        {
            // 设备总数
            Dictionary<string, object> nameandid = await db.Queryable<Device>().Where(d => d.Eid == eid).Where(d => d.IsDel == 0).ToDictionaryAsync(d => SqlFunc.MergeString(d.Number, d.Name), d => d.Id);

            if (nameandid == null)
            {
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = -1,
                    Succeeded = false,
                    Data = null,
                    Errors = null,
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }

            Dictionary<string, int> data = new();
            // 计算时间范围段
            DateTime begintime = DateTime.Now;
            DateTime endtime = DateTime.Now;
            DateTime ct = DateTime.Now;
            if (rt.Equals("本周"))
            {
                begintime = ct.AddDays(1 - (ct.DayOfWeek == DayOfWeek.Sunday ? 7 : int.Parse(ct.DayOfWeek.ToString("d")))); // 本周一
                endtime = begintime.AddDays(6); // 本周日
                // 今天厂商设备故障数
                foreach ((string name, object id) in nameandid)
                {
                    int trouble_device_count = await db.Queryable<NoticeRepair>().Where(nr => nr.Eid == eid)
                        .Where(nr => nr.TroubleTime.Date >= begintime.Date && nr.TroubleTime.Date < endtime.Date)
                        .Where(nr => nr.Dvid == long.Parse(id.ToString()))
                        .CountAsync();
                    data.Add(name, trouble_device_count);
                }
            }

            if (rt.Equals("本月"))
            {
                begintime = ct.AddDays(1 - ct.Day);  //本月月初
                endtime = begintime.AddMonths(1).AddDays(-1);  //本月月末
                // 今天厂商设备故障数
                foreach ((string name, object id) in nameandid)
                {
                    int trouble_device_count = await db.Queryable<NoticeRepair>().Where(nr => nr.Eid == eid)
                        .Where(nr => nr.TroubleTime.Date >= begintime.Date && nr.TroubleTime.Date < endtime.Date)
                        .Where(nr => nr.Dvid == long.Parse(id.ToString()))
                        .CountAsync();
                    data.Add(name, trouble_device_count);
                }
            }

            if (rt.Equals("本年"))
            {
                begintime = new DateTime(ct.Year, 1, 1);  //本年年初
                endtime = new DateTime(ct.Year, 12, 31);  //本年年末
                // 今天厂商设备故障数
                foreach ((string name, object id) in nameandid)
                {
                    int trouble_device_count = await db.Queryable<NoticeRepair>().Where(nr => nr.Eid == eid)
                        .Where(nr => nr.TroubleTime.Date >= begintime.Date && nr.TroubleTime.Date < endtime.Date)
                        .Where(nr => nr.Dvid == long.Parse(id.ToString()))
                        .CountAsync();
                    data.Add(name, trouble_device_count);
                }
            }

            //data = (Dictionary<string, int>)((Dictionary<string, int>)(from od in data orderby od.Value descending select od)).Take(5);
            data = data.OrderByDescending(pair => pair.Value).Take(5).ToDictionary(pair => pair.Key, pair => pair.Value);

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }*/

        /// <summary>
        /// 设备故障次数Top5
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="rt"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostShebeiguzhangcishu([FromForm] long eid, [FromForm] string rt)
        {
            dynamic data = null;
            // 计算时间范围段
            DateTime begintime = DateTime.Now;
            DateTime endtime = DateTime.Now;
            DateTime ct = DateTime.Now;
            if (rt.Equals("本周"))
            {
                begintime = ct.AddDays(1 - (ct.DayOfWeek == DayOfWeek.Sunday ? 7 : int.Parse(ct.DayOfWeek.ToString("d")))); // 本周一
                endtime = begintime.AddDays(6); // 本周日
                // 本周厂商设备故障数
                data = await db.Queryable<NoticeRepair>()
                    .Where(nr => nr.IsDel == 0)
                    .Where(nr => nr.TroubleTime.Date >= begintime.Date && nr.TroubleTime.Date <= endtime.Date)
                    .GroupBy(nr => nr.Dvname)
                    .Select(nr => new { Total = SqlFunc.AggregateCount("*"), DvName = nr.Dvname})
                    .OrderBy(bx => bx.Total, OrderByType.Desc)
                    .Take(5)
                    .ToListAsync();
            }

            if (rt.Equals("本月"))
            {
                begintime = ct.AddDays(1 - ct.Day);  //本月月初
                endtime = begintime.AddMonths(1).AddDays(-1);  //本月月末
                // 本月厂商设备故障数
                data = await db.Queryable<NoticeRepair>()
                    .Where(nr => nr.IsDel == 0)
                    .Where(nr => nr.TroubleTime.Date >= begintime.Date && nr.TroubleTime.Date <= endtime.Date)
                    .GroupBy(nr => nr.Dvname)
                    .Select(nr => new { Total = SqlFunc.AggregateCount("*"), DvName = nr.Dvname })
                    .OrderBy(bx => bx.Total, OrderByType.Desc)
                    .Take(5)
                    .ToListAsync();
            }

            if (rt.Equals("本年"))
            {
                begintime = new DateTime(ct.Year, 1, 1);  //本年年初
                endtime = new DateTime(ct.Year, 12, 31);  //本年年末
                // 本年厂商设备故障数
                data = await db.Queryable<NoticeRepair>()
                    .Where(nr => nr.IsDel == 0)
                    .Where(nr => nr.TroubleTime.Date >= begintime.Date && nr.TroubleTime.Date <= endtime.Date)
                    .GroupBy(nr => nr.Dvname)
                    .Select(nr => new { Total = SqlFunc.AggregateCount("*"), DvName = nr.Dvname })
                    .OrderBy(bx => bx.Total, OrderByType.Desc)
                    .Take(5)
                    .ToListAsync();
            }

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 设备停机时间Top5
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="rt"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostShebeitingjishijian([FromForm] long eid, [FromForm] string rt)
        {
            List<NrWorkOrder> nrWorkOrders = new();
            // 计算时间范围段
            DateTime begintime = DateTime.Now;
            DateTime endtime = DateTime.Now;
            DateTime ct = DateTime.Now;
            if (rt.Equals("本周"))
            {
                begintime = ct.AddDays(1 - (ct.DayOfWeek == DayOfWeek.Sunday ? 7 : int.Parse(ct.DayOfWeek.ToString("d")))); // 本周一
                endtime = begintime.AddDays(6); // 本周日
                // 本周厂商设备故障数
                nrWorkOrders = await db.Queryable<NrWorkOrder>()
                    .Mapper(wo => wo.NoticeRepair, wo => wo.NpId, wo => wo.NoticeRepair.Id)
                    //.GroupBy(wo => new { wo.Dvid, wo.Dvname })
                    .Where(wo => wo.Eid == eid)
                    .Where(wo => wo.Status == "已完成")
                    .Where(wo => wo.NoticeRepair.IsHalt == 1)
                    .Where(wo => wo.NoticeRepair.TroubleTime.Date >= begintime.Date && wo.NoticeRepair.TroubleTime.Date <= endtime.Date)
                    //.Select(wo => new { DvName = wo.Dvname, TotalManHour = SqlFunc.AggregateSum(wo.SjManHour) })
                    //.OrderBy(nc => nc.TotalManHour, OrderByType.Desc)
                    .ToListAsync();
            }

            if (rt.Equals("本月"))
            {
                begintime = ct.AddDays(1 - ct.Day);  //本月月初
                endtime = begintime.AddMonths(1).AddDays(-1);  //本月月末
                // 本月厂商设备故障数
                nrWorkOrders = await db.Queryable<NrWorkOrder>()
                    .Mapper(wo => wo.NoticeRepair, wo => wo.NpId, wo => wo.NoticeRepair.Id)
                    //.GroupBy(wo => wo.Dvid)
                    .Where(wo => wo.Eid == eid)
                    .Where(wo => wo.Status == "已完成")
                    .Where(wo => wo.NoticeRepair.TroubleTime.Date >= begintime.Date && wo.NoticeRepair.TroubleTime.Date <= endtime.Date)
                    //.Select(wo => new { DvName = wo.Dvname, TotalManHour = SqlFunc.AggregateSum(wo.SjManHour) })
                    //.OrderBy(nc => nc.TotalManHour, OrderByType.Desc)
                    //.Take(5)
                    .ToListAsync();
            }

            if (rt.Equals("本年"))
            {
                begintime = new DateTime(ct.Year, 1, 1);  //本年年初
                endtime = new DateTime(ct.Year, 12, 31);  //本年年末
                // 本年厂商设备故障数
                nrWorkOrders = await db.Queryable<NrWorkOrder>()
                    .Mapper(wo => wo.NoticeRepair, wo => wo.NpId, wo => wo.NoticeRepair.Id)
                    //.GroupBy(wo => wo.Dvid)
                    .Where(wo => wo.Eid == eid)
                    .Where(wo => wo.Status == "已完成")
                    .Where(wo => wo.NoticeRepair.TroubleTime.Date >= begintime.Date && wo.NoticeRepair.TroubleTime.Date <= endtime.Date)
                    //.Select(wo => new { DvName = wo.Dvname, TotalManHour = SqlFunc.AggregateSum(wo.SjManHour) })
                    //.OrderBy(nc => nc.TotalManHour, OrderByType.Desc)
                    //.Take(5)
                    .ToListAsync();
            }

            //data = (Dictionary<string, double>)((Dictionary<string, int>)(from od in data orderby od.Value descending select od)).Take(5);
            //data = data.OrderByDescending(pair => pair.Value).Take(5).ToDictionary(pair => pair.Key, pair => pair.Value);
            var data = nrWorkOrders.GroupBy(g => g.Dvid).Select(innerList => new {
                DvName = innerList.FirstOrDefault().Dvname,
                TotalMinutes = Math.Round(innerList.Sum(nrwo => (nrwo.SjEndTime - nrwo.NoticeRepair.TroubleTime).TotalSeconds / 3600), 2)
            }).OrderByDescending(res => res.TotalMinutes).Take(5);

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }


        /*public async Task<IActionResult> PostShebeiguzhangtongjixiangqing([FromForm] long eid, [FromForm] long aeid, [FromForm] long dvtid, [FromForm] long dvid, [FromForm] DateTime begintime, [FromForm] DateTime endtime)
        {
            int total = await db.Queryable<Device>().Where(d => d.Eid == eid).Where(d => d.IsDel == 0).CountAsync();
            // 设备ID
            List<long> dvids = await db.Queryable<Device>()
                .Where(d => d.Eid == eid)
                .WhereIF(aeid != 0, d => d.Aeid == aeid)
                .WhereIF(dvtid != 0, d => d.Dvtid == dvtid)
                .WhereIF(dvid != 0, d => d.Id == dvid)
                .Select(d => d.Id)
                .ToListAsync();
            dvids.Add(-1);

            Dictionary<string, double> data = new();
            //Dictionary<string, List<NoticeRepair>> list_data = new();
            if ((endtime - begintime).TotalDays >= 45)
            { // 按月展示
                for (int i = begintime.Month; i <= endtime.Month; i++)
                {
                    // 本月开始时间和结束时间
                    DateTime select_end_time = begintime.AddMonths(1).AddDays(-1);
                    // 今天设备故障数
                    int trouble_count = await db.Queryable<NoticeRepair>().Where(nr => nr.Eid == eid)
                        .Where(nr => dvids.Contains(nr.Dvid))
                        .Where(nr => nr.TroubleTime.Date >= begintime.Date && nr.TroubleTime.Date <= select_end_time.Date)
                        .CountAsync();
                    data.Add($"{begintime.Month}月", (double)trouble_count / total * 100);

                    //List<NoticeRepair> noticerepairs = await db.Queryable<NoticeRepair>().Where(nr => nr.Eid == eid)
                    //    .Where(nr => dvids.Contains(nr.Dvid))
                    //    .Where(nr => nr.TroubleTime.Date >= begintime.Date && nr.TroubleTime.Date <= select_end_time.Date)
                    //    .ToListAsync();
                    //list_data.Add($"{begintime.Month}月", noticerepairs);
                    begintime = begintime.AddMonths(1);
                }
            }
            else
            {
                // 按天展示
                for (int i = 0; i <= (endtime - begintime).TotalDays; i++)
                {
                    // 本月当前时间
                    DateTime select_time = begintime.AddDays(i);
                    // 今天设备故障数
                    int trouble_count = await db.Queryable<NoticeRepair>().Where(nr => nr.Eid == eid)
                        .Where(nr => dvids.Contains(nr.Dvid))
                        .Where(nr => nr.TroubleTime.Date == select_time.Date)
                        .CountAsync();
                    data.Add(select_time.ToString("yyyy-MM-dd"), (double)trouble_count / total * 100);

                    //List<NoticeRepair> noticerepairs = await db.Queryable<NoticeRepair>().Where(nr => nr.Eid == eid)
                    //    .Where(nr => dvids.Contains(nr.Dvid))
                    //    .Where(nr => nr.TroubleTime.Date == begintime.Date)
                    //    .ToListAsync();
                    //list_data.Add(select_time.ToString("yyyy-MM-dd"), noticerepairs);
                }
            }

            List<NoticeRepair> noticerepairs = await db.Queryable<NoticeRepair>().Where(nr => nr.Eid == eid)
                        .Mapper(nr => nr.Device, nr => nr.Dvid, nr => nr.Device.Id)
                        .Where(nr => dvids.Contains(nr.Dvid))
                        .Where(nr => nr.TroubleTime.Date >= begintime.Date && nr.TroubleTime.Date <= endtime.Date)
                        .Mapper(nr => nr.NoticeRepairResult, nr => nr.Id, nr => nr.NoticeRepairResult.NpId)
                        .ToListAsync();

            UnifyContext.Fill(new { ListData = noticerepairs });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }*/

        /// <summary>
        /// 设备故障统计详情
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="aeid"></param>
        /// <param name="dvtid"></param>
        /// <param name="dvid"></param>
        /// <param name="begintime"></param>
        /// <param name="endtime"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostShebeiguzhangtongjixiangqing([FromForm] long eid, [FromForm] long aeid, [FromForm] long dvtid, [FromForm] long dvid, [FromForm] DateTime begintime, [FromForm] DateTime endtime)
        {
            DateTime temp = begintime;
            Dictionary<string, int> data = new();
            if ((endtime - begintime).TotalDays >= 45)
            { // 按月展示
                for (int i = begintime.Month; i <= endtime.Month; i++)
                {
                    // 本月开始时间和结束时间
                    DateTime select_end_time = begintime.AddMonths(1).AddDays(-1);
                    // 今天设备故障数
                    int trouble_count = await db.Queryable<NoticeRepair>()
                        .Where(nr => nr.IsDel == 0)
                        .Where(nr => nr.Eid == eid)
                        .WhereIF(aeid != 0, nr => nr.AeId == aeid)
                        .WhereIF(dvid != 0, nr => nr.Dvid == dvid)
                        .WhereIF(dvtid != 0, nr => nr.Dvtid == dvtid)
                        .Where(nr => nr.TroubleTime.Date >= begintime.Date && nr.TroubleTime.Date <= select_end_time.Date)
                        .CountAsync();
                    data.Add($"{begintime.Month}月", trouble_count);

                    begintime = begintime.AddMonths(1);
                }
            }
            else
            {
                // 按天展示
                for (int i = 0; i <= (endtime - begintime).TotalDays; i++)
                {
                    // 本月当前时间
                    DateTime select_time = begintime.AddDays(i);
                    // 今天设备故障数
                    int trouble_count = await db.Queryable<NoticeRepair>()
                        .Where(nr => nr.IsDel == 0)
                        .Where(nr => nr.Eid == eid)
                        .WhereIF(aeid != 0, nr => nr.AeId == aeid)
                        .WhereIF(dvid != 0, nr => nr.Dvid == dvid)
                        .WhereIF(dvtid != 0, nr => nr.Dvtid == dvtid)
                        .Where(nr => nr.TroubleTime.Date == select_time.Date)
                        .CountAsync();
                    data.Add(select_time.ToString("yyyy-MM-dd"), trouble_count);
                }
            }

            List<NoticeRepair> noticerepairs = await db.Queryable<NoticeRepair>()
                .Mapper(nr => nr.Device, nr => nr.Dvid, nr => nr.Device.Id)
                .Where(nr => nr.Eid == eid)
                .WhereIF(aeid != 0, nr => nr.AeId == aeid)
                .WhereIF(dvid != 0, nr => nr.Dvid == dvid)
                .WhereIF(dvtid != 0, nr => nr.Dvtid == dvtid)
                .Where(nr => nr.TroubleTime.Date >= temp.Date && nr.TroubleTime.Date <= endtime.Date)
                .ToListAsync();

            UnifyContext.Fill(new { ListData = noticerepairs });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 设备故障统计详情导出
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="aeid"></param>
        /// <param name="dvtid"></param>
        /// <param name="dvid"></param>
        /// <param name="begintime"></param>
        /// <param name="endtime"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostShebeiguzhangtongjixiangqingexport([FromForm] long eid, [FromForm] long aeid, [FromForm] long dvtid, [FromForm] long dvid, [FromForm] DateTime begintime, [FromForm] DateTime endtime)
        {
            List<NoticeRepair> noticerepairs = await db.Queryable<NoticeRepair>()
                .Mapper(nr => nr.Device, nr => nr.Dvid, nr => nr.Device.Id)
                .Where(nr => nr.IsDel == 0)
                .Where(nr => nr.Eid == eid)
                .WhereIF(aeid != 0, nr => nr.AeId == aeid)
                .WhereIF(dvid != 0, nr => nr.Dvid == dvid)
                .WhereIF(dvtid != 0, nr => nr.Dvtid == dvtid)
                .Where(nr => nr.TroubleTime.Date >= begintime.Date && nr.TroubleTime.Date <= endtime.Date)
                .ToListAsync();

            IExporter exporter = new ExcelExporter();
            await exporter.Export(@"wwwroot/download/baoxiu/设备故障统计详情.xlsx", noticerepairs.Adapt<List<DeviceTroubleTongJiXiangQingDto>>());

            JObject data = new();
            data.Add("url", $"http://{App.HttpContext.Request.Host.Value}/download/baoxiu/设备故障统计详情.xlsx");
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
        /// <summary>
        /// 报表管理-计划工单-计划工单占比
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="rt"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostTaskplanworkorderzhanbi([FromForm] long eid, [FromForm] string rt)
        {
            // 总共的计划工单
            int wo_total = await db.Queryable<TpWorkOrder>()
                .Where(wo => wo.Eid == eid)
                .CountAsync();

            if (wo_total == 0)
            {
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = -1,
                    Succeeded = false,
                    Data = null,
                    Errors = null,
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }

            Dictionary<string, int> data = new();
            // 计算时间范围段
            DateTime begintime = DateTime.Now;
            DateTime endtime = DateTime.Now;
            DateTime ct = DateTime.Now;

            if (rt.Equals("今日"))
            {
                data.Add("巡检计划", (await db.Queryable<TpWorkOrder>()
                    .Where(wo => wo.Eid == eid)
                    .Where(wo => wo.Type == "巡检工单")
                    .Where(wo => wo.Created.Date == DateTime.Now.Date)
                    .CountAsync()));
                data.Add("点检计划", (await db.Queryable<TpWorkOrder>()
                    .Where(wo => wo.Eid == eid)
                    .Where(wo => wo.Type == "点检工单")
                    .Where(wo => wo.Created.Date == DateTime.Now.Date)
                    .CountAsync()));
                data.Add("保养计划", (await db.Queryable<TpWorkOrder>()
                    .Where(wo => wo.Eid == eid)
                    .Where(wo => wo.Type == "保养工单")
                    .Where(wo => wo.Created.Date == DateTime.Now.Date)
                    .CountAsync()));
            }

            if (rt.Equals("本周"))
            {
                begintime = ct.AddDays(1 - (ct.DayOfWeek == DayOfWeek.Sunday ? 7 : int.Parse(ct.DayOfWeek.ToString("d")))); // 本周一
                endtime = begintime.AddDays(6); // 本周日
                data.Add("巡检计划", (await db.Queryable<TpWorkOrder>()
                    .Where(wo => wo.Eid == eid)
                    .Where(wo => wo.Type == "巡检工单")
                    .Where(wo => wo.Created.Date >= begintime.Date && wo.Created <= endtime.Date)
                    .CountAsync()));
                data.Add("点检计划", (await db.Queryable<TpWorkOrder>()
                    .Where(wo => wo.Eid == eid)
                    .Where(wo => wo.Type == "点检工单")
                    .Where(wo => wo.Created.Date >= begintime.Date && wo.Created <= endtime.Date)
                    .CountAsync()));
                data.Add("保养计划", (await db.Queryable<TpWorkOrder>()
                    .Where(wo => wo.Eid == eid)
                    .Where(wo => wo.Type == "保养工单")
                    .Where(wo => wo.Created.Date >= begintime.Date && wo.Created <= endtime.Date)
                    .CountAsync()));
            }

            if (rt.Equals("本月"))
            {
                begintime = ct.AddDays(1 - ct.Day);  //本月月初
                endtime = begintime.AddMonths(1).AddDays(-1);  //本月月末
                data.Add("巡检计划", (await db.Queryable<TpWorkOrder>()
                    .Where(wo => wo.Eid == eid)
                    .Where(wo => wo.Type == "巡检工单")
                    .Where(wo => wo.Created.Date >= begintime.Date && wo.Created <= endtime.Date)
                    .CountAsync()));
                data.Add("点检计划", (await db.Queryable<TpWorkOrder>()
                    .Where(wo => wo.Eid == eid)
                    .Where(wo => wo.Type == "点检工单")
                    .Where(wo => wo.Created.Date >= begintime.Date && wo.Created <= endtime.Date)
                    .CountAsync()));
                data.Add("保养计划", (await db.Queryable<TpWorkOrder>()
                    .Where(wo => wo.Eid == eid)
                    .Where(wo => wo.Type == "保养工单")
                    .Where(wo => wo.Created.Date >= begintime.Date && wo.Created <= endtime.Date)
                    .CountAsync()));
            }

            if (rt.Equals("本年"))
            {
                begintime = new DateTime(ct.Year, 1, 1);  //本年年初
                endtime = new DateTime(ct.Year, 12, 31);  //本年年末
                data.Add("巡检计划", (await db.Queryable<TpWorkOrder>()
                    .Where(wo => wo.Eid == eid)
                    .Where(wo => wo.Type == "巡检工单")
                    .Where(wo => wo.Created.Date >= begintime.Date && wo.Created <= endtime.Date)
                    .CountAsync()));
                data.Add("点检计划", (await db.Queryable<TpWorkOrder>()
                    .Where(wo => wo.Eid == eid)
                    .Where(wo => wo.Type == "点检工单")
                    .Where(wo => wo.Created.Date >= begintime.Date && wo.Created <= endtime.Date)
                    .CountAsync()));
                data.Add("保养计划", (await db.Queryable<TpWorkOrder>()
                    .Where(wo => wo.Eid == eid)
                    .Where(wo => wo.Type == "保养工单")
                    .Where(wo => wo.Created.Date >= begintime.Date && wo.Created <= endtime.Date)
                    .CountAsync()));
            }

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 报表管理-计划工单-预防性维护计划完成率
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="rt"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostYufangxingweihujihuawanchenglv([FromForm] long eid, [FromForm] string rt)
        {
            DateTime begintime = DateTime.Now;
            DateTime endtime = DateTime.Now;

            JObject data = new();
            int baoyangjihua_total = await db.Queryable<TpWorkOrder>().Where(wo => wo.Eid == eid).Where(wo => wo.Type == "保养工单").CountAsync();
            int dianjianjihua_total = await db.Queryable<TpWorkOrder>().Where(wo => wo.Eid == eid).Where(wo => wo.Type == "点检工单").CountAsync();
            int xunjianjihua_total = await db.Queryable<TpWorkOrder>().Where(wo => wo.Eid == eid).Where(wo => wo.Type == "巡检工单").CountAsync();

            try
            {
                if (rt.Equals("今日"))
                {

                    int baoyangjihua = await db.Queryable<TpWorkOrder>().Where(wo => wo.Eid == eid).Where(wo => wo.Type == "保养工单").Where(wo => wo.Status == "已完成").Where(wo => wo.SjEndTime.Date == DateTime.Now.Date).CountAsync();

                    int dianjianjihua = await db.Queryable<TpWorkOrder>().Where(wo => wo.Eid == eid).Where(wo => wo.Type == "点检工单").Where(wo => wo.Status == "已完成").Where(wo => wo.SjEndTime.Date == DateTime.Now.Date).CountAsync();

                    int xunjianjihua = await db.Queryable<TpWorkOrder>().Where(wo => wo.Eid == eid).Where(wo => wo.Type == "巡检工单").Where(wo => wo.Status == "已完成").Where(wo => wo.SjEndTime.Date == DateTime.Now.Date).CountAsync();
                    data.Add("保养计划", baoyangjihua_total == 0 ? 0 : (double)baoyangjihua / baoyangjihua_total * 100);
                    data.Add("点检计划", dianjianjihua_total == 0 ? 0 : (double)dianjianjihua / dianjianjihua_total * 100);
                    data.Add("巡检计划", xunjianjihua_total == 0 ? 0 : (double)xunjianjihua / xunjianjihua_total * 100);
                }

                if (rt.Equals("本周"))
                {
                    begintime = begintime.AddDays(1 - int.Parse(begintime.DayOfWeek.ToString("d"))); // 本周一
                    endtime = begintime.AddDays(6); // 本周日

                    int baoyangjihua = await db.Queryable<TpWorkOrder>().Where(wo => wo.Eid == eid).Where(wo => wo.Type == "保养工单").Where(wo => wo.Status == "已完成").Where(wo => wo.SjEndTime.Date >= begintime.Date && wo.SjEndTime.Date <= endtime.Date).CountAsync();

                    int dianjianjihua = await db.Queryable<TpWorkOrder>().Where(wo => wo.Eid == eid).Where(wo => wo.Type == "点检工单").Where(wo => wo.Status == "已完成").Where(wo => wo.SjEndTime.Date >= begintime.Date && wo.SjEndTime.Date <= endtime.Date).CountAsync();

                    int xunjianjihua = await db.Queryable<TpWorkOrder>().Where(wo => wo.Eid == eid).Where(wo => wo.Type == "巡检工单").Where(wo => wo.Status == "已完成").Where(wo => wo.SjEndTime.Date >= begintime.Date && wo.SjEndTime.Date <= endtime.Date).CountAsync();
                    data.Add("保养计划", baoyangjihua_total == 0 ? 0 : (double)baoyangjihua / baoyangjihua_total * 100);
                    data.Add("点检计划", dianjianjihua_total == 0 ? 0 : (double)dianjianjihua / dianjianjihua_total * 100);
                    data.Add("巡检计划", xunjianjihua_total == 0 ? 0 : (double)xunjianjihua / xunjianjihua_total * 100);
                }

                if (rt.Equals("本月"))
                {
                    begintime = begintime.AddDays(1 - begintime.Day);  //本月月初
                    endtime = begintime.AddMonths(1).AddDays(-1);  //本月月末

                    int baoyangjihua = await db.Queryable<TpWorkOrder>().Where(wo => wo.Eid == eid).Where(wo => wo.Type == "保养工单").Where(wo => wo.Status == "已完成").Where(wo => wo.SjEndTime.Date >= begintime.Date && wo.SjEndTime.Date <= endtime.Date).CountAsync();

                    int dianjianjihua = await db.Queryable<TpWorkOrder>().Where(wo => wo.Eid == eid).Where(wo => wo.Type == "点检工单").Where(wo => wo.Status == "已完成").Where(wo => wo.SjEndTime.Date >= begintime.Date && wo.SjEndTime.Date <= endtime.Date).CountAsync();

                    int xunjianjihua = await db.Queryable<TpWorkOrder>().Where(wo => wo.Eid == eid).Where(wo => wo.Type == "巡检工单").Where(wo => wo.Status == "已完成").Where(wo => wo.SjEndTime.Date >= begintime.Date && wo.SjEndTime.Date <= endtime.Date).CountAsync();
                    data.Add("保养计划", baoyangjihua_total == 0 ? 0 : (double)baoyangjihua / baoyangjihua_total * 100);
                    data.Add("点检计划", dianjianjihua_total == 0 ? 0 : (double)dianjianjihua / dianjianjihua_total * 100);
                    data.Add("巡检计划", xunjianjihua_total == 0 ? 0 : (double)xunjianjihua / xunjianjihua_total * 100);
                }

                if (rt.Equals("本年"))
                {
                    begintime = new DateTime(begintime.Year, 1, 1);  //本年年初
                    endtime = new DateTime(endtime.Year, 12, 31);  //本年年末

                    int baoyangjihua = await db.Queryable<TpWorkOrder>().Where(wo => wo.Eid == eid).Where(wo => wo.Type == "保养工单").Where(wo => wo.Status == "已完成").Where(wo => wo.SjEndTime.Date >= begintime.Date && wo.SjEndTime.Date <= endtime.Date).CountAsync();

                    int dianjianjihua = await db.Queryable<TpWorkOrder>().Where(wo => wo.Eid == eid).Where(wo => wo.Type == "点检工单").Where(wo => wo.Status == "已完成").Where(wo => wo.SjEndTime.Date >= begintime.Date && wo.SjEndTime.Date <= endtime.Date).CountAsync();

                    int xunjianjihua = await db.Queryable<TpWorkOrder>().Where(wo => wo.Eid == eid).Where(wo => wo.Type == "巡检工单").Where(wo => wo.Status == "已完成").Where(wo => wo.SjEndTime.Date >= begintime.Date && wo.SjEndTime.Date <= endtime.Date).CountAsync();
                    data.Add("保养计划", baoyangjihua_total == 0 ? 0 : (double)baoyangjihua / baoyangjihua_total * 100);
                    data.Add("点检计划", dianjianjihua_total == 0 ? 0 : (double)dianjianjihua / dianjianjihua_total * 100);
                    data.Add("巡检计划", xunjianjihua_total == 0 ? 0 : (double)xunjianjihua / xunjianjihua_total * 100);
                }

                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = 200,
                    Succeeded = true,
                    Data = data,
                    Errors = null,
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }
            catch (Exception e)
            {
                data.Add("保养计划", 0);
                data.Add("点检计划", 0);
                data.Add("巡检计划", 0);
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = 200,
                    Succeeded = true,
                    Data = data,
                    Errors = e.Message,
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }


        }

        /// <summary>
        /// 报表管理-计划工单-计划工单工时消耗对比
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="rt"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostJihuagongdangongshixiaohaoduibi([FromForm] long eid, [FromForm] string rt)
        {
            List<TpWorkOrder> workorders = new();
            // 计算时间范围段
            DateTime begintime = DateTime.Now;
            DateTime endtime = DateTime.Now;
            DateTime ct = DateTime.Now;
            if (rt.Equals("本周"))
            {
                begintime = ct.AddDays(1 - (ct.DayOfWeek == DayOfWeek.Sunday ? 7 : int.Parse(ct.DayOfWeek.ToString("d")))); // 本周一
                endtime = begintime.AddDays(6); // 本周日

                workorders = await db.Queryable<TpWorkOrder>()
                        .Where(wo => wo.Eid == eid)
                        .Where(wo => wo.Status == "已完成")
                        .Where(wo => wo.SjEndTime.Date >= begintime.Date && wo.SjEndTime <= endtime.Date)
                        .ToListAsync();
            }

            if (rt.Equals("本月"))
            {
                begintime = ct.AddDays(1 - ct.Day);  //本月月初
                endtime = begintime.AddMonths(1).AddDays(-1);  //本月月末

                workorders = await db.Queryable<TpWorkOrder>()
                        .Where(wo => wo.Eid == eid)
                        .Where(wo => wo.Status == "已完成")
                        .Where(wo => wo.SjEndTime.Date >= begintime.Date && wo.SjEndTime <= endtime.Date)
                        .ToListAsync();
            }

            if (rt.Equals("本年"))
            {
                begintime = new DateTime(ct.Year, 1, 1);  //本年年初
                endtime = new DateTime(ct.Year, 12, 31);  //本年年末

                workorders = await db.Queryable<TpWorkOrder>()
                        .Where(wo => wo.Eid == eid)
                        .Where(wo => wo.Status == "已完成")
                        .Where(wo => wo.SjEndTime.Date >= begintime.Date && wo.SjEndTime <= endtime.Date)
                        .ToListAsync();
            }

            var data = workorders.GroupBy(wo => wo.SjWxEpRealname).Select(res => new {
                Realname = res.FirstOrDefault().SjWxEpRealname,
                JhTotal = res.Sum(d => d.ManHour),
                SjTotal = res.Sum(d => d.SjManHour)
            });

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 报表管理-维修工单-维修工单完成占比
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="rt"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostWeixiugongdanzhanbi([FromForm] long eid, [FromForm] string rt)
        {
            Dictionary<string, int> data = new();
            // 计算时间范围段
            DateTime begintime = DateTime.Now;
            DateTime endtime = DateTime.Now;
            DateTime ct = DateTime.Now;

            if (rt.Equals("今日"))
            {
                data.Add("已完成", (await db.Queryable<NrWorkOrder>()
                    .Where(wo => wo.Eid == eid)
                    .Where(wo => wo.SjEndTime.Date == DateTime.Now.Date)
                    .Where(wo => wo.Status == "已完成")
                    .CountAsync()));
                data.Add("未完成", (await db.Queryable<NrWorkOrder>()
                    .Where(wo => wo.Eid == eid)
                    .Where(wo => wo.BeginTime.Date == DateTime.Now.Date)
                    .Where(wo => wo.Status != "已完成")
                    .CountAsync()));
            }

            if (rt.Equals("本周"))
            {
                begintime = ct.AddDays(1 - (ct.DayOfWeek == DayOfWeek.Sunday ? 7 : int.Parse(ct.DayOfWeek.ToString("d")))); // 本周一
                endtime = begintime.AddDays(6); // 本周日
                data.Add("已完成", (await db.Queryable<NrWorkOrder>()
                    .Where(wo => wo.Eid == eid)
                    .Where(wo => wo.Status == "已完成")
                    .Where(wo => wo.SjEndTime.Date >= begintime.Date && wo.SjEndTime <= endtime.Date)
                    .CountAsync()));
                data.Add("未完成", (await db.Queryable<NrWorkOrder>()
                    .Where(wo => wo.Eid == eid)
                    .Where(wo => wo.Status != "已完成")
                    .Where(wo => wo.BeginTime.Date >= begintime.Date && wo.BeginTime <= endtime.Date)
                    .CountAsync()));
            }

            if (rt.Equals("本月"))
            {
                begintime = ct.AddDays(1 - ct.Day);  //本月月初
                endtime = begintime.AddMonths(1).AddDays(-1);  //本月月末
                data.Add("已完成", (await db.Queryable<NrWorkOrder>()
                    .Where(wo => wo.Eid == eid)
                    .Where(wo => wo.Status == "已完成")
                    .Where(wo => wo.SjEndTime.Date >= begintime.Date && wo.SjEndTime <= endtime.Date)
                    .CountAsync()));
                data.Add("未完成", (await db.Queryable<NrWorkOrder>()
                    .Where(wo => wo.Eid == eid)
                    .Where(wo => wo.Status != "已完成")
                    .Where(wo => wo.BeginTime.Date >= begintime.Date && wo.BeginTime <= endtime.Date)
                    .CountAsync()));
            }

            if (rt.Equals("本年"))
            {
                begintime = new DateTime(ct.Year, 1, 1);  //本年年初
                endtime = new DateTime(ct.Year, 12, 31);  //本年年末
                data.Add("已完成", (await db.Queryable<NrWorkOrder>()
                    .Where(wo => wo.Eid == eid)
                    .Where(wo => wo.Status == "已完成")
                    .Where(wo => wo.SjEndTime.Date >= begintime.Date && wo.SjEndTime <= endtime.Date)
                    .CountAsync()));
                data.Add("未完成", (await db.Queryable<NrWorkOrder>()
                    .Where(wo => wo.Eid == eid)
                    .Where(wo => wo.Status != "已完成")
                    .Where(wo => wo.BeginTime.Date >= begintime.Date && wo.BeginTime <= endtime.Date)
                    .CountAsync()));
            }

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 报表管理-维修工单-设备总停机时间
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="rt"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostShebeizongtingjishijian([FromForm] long eid, [FromForm] string rt)
        {
            Dictionary<string, decimal> data = new();
            // 计算时间范围段
            DateTime begintime = DateTime.Now;
            DateTime endtime = DateTime.Now;
            DateTime ct = DateTime.Now;
            if (rt.Equals("本周"))
            {
                begintime = ct.AddDays(1 - (ct.DayOfWeek == DayOfWeek.Sunday ? 7 : int.Parse(ct.DayOfWeek.ToString("d")))); // 本周一
                endtime = begintime.AddDays(6); // 本周日
                for (int i = 0; i < 7; i++)
                {
                    // 本周当前时间
                    DateTime select_time = begintime.AddDays(i);
                    // 当前时间段设备停机时间
                    List<NrWorkOrder> nrWorkOrders = await db.Queryable<NrWorkOrder>()
                    .Mapper(wo => wo.NoticeRepair, wo => wo.NpId, wo => wo.NoticeRepair.Id)
                    .Where(wo => wo.Eid == eid)
                    .Where(wo => wo.Status == "已完成")
                    .Where(wo => wo.NoticeRepair.IsHalt == 1)
                    .Where(wo => wo.SjEndTime.Date == select_time.Date)
                    .ToListAsync();
                    decimal total = 0;
                    foreach (var nrWorkOrder in nrWorkOrders)
                    {
                        total += (nrWorkOrder.SjEndTime - nrWorkOrder.NoticeRepair.TroubleTime).TotalHours.ToDecimal();
                    }
                    data.Add(select_time.ToString("yyyy-MM-dd"), total);
                }
            }

            if (rt.Equals("本月"))
            {
                begintime = ct.AddDays(1 - ct.Day);  //本月月初
                endtime = begintime.AddMonths(1).AddDays(-1);  //本月月末
                for (int i = 0; i < endtime.Day; i++)
                {
                    // 本月当前时间
                    DateTime select_time = begintime.AddDays(i);
                    // 当前时间段设备停机时间
                    List<NrWorkOrder> nrWorkOrders = await db.Queryable<NrWorkOrder>()
                    .Mapper(wo => wo.NoticeRepair, wo => wo.NpId, wo => wo.NoticeRepair.Id)
                    .Where(wo => wo.Eid == eid)
                    .Where(wo => wo.Status == "已完成")
                    .Where(wo => wo.NoticeRepair.IsHalt == 1)
                    .Where(wo => wo.SjEndTime.Date == select_time.Date)
                    .ToListAsync();
                    decimal total = 0;
                    foreach (var nrWorkOrder in nrWorkOrders)
                    {
                        total += (nrWorkOrder.SjEndTime - nrWorkOrder.NoticeRepair.TroubleTime).TotalHours.ToDecimal();
                    }
                    data.Add(select_time.ToString("yyyy-MM-dd"), total);
                }
            }

            if (rt.Equals("本年"))
            {
                begintime = new DateTime(ct.Year, 1, 1);  //本年年初
                for (int i = 0; i < 12; i++)
                {
                    // 本月开始时间和结束时间
                    DateTime select_begin_time = begintime.AddMonths(i);
                    DateTime select_end_time = begintime.AddMonths(i + 1);
                    // 当前时间段设备停机时间
                    List<NrWorkOrder> nrWorkOrders = await db.Queryable<NrWorkOrder>()
                    .Mapper(wo => wo.NoticeRepair, wo => wo.NpId, wo => wo.NoticeRepair.Id)
                    .Where(wo => wo.Eid == eid)
                    .Where(wo => wo.Status == "已完成")
                    .Where(wo => wo.NoticeRepair.IsHalt == 1)
                    .Where(wo => wo.SjEndTime.Date >= select_begin_time.Date && wo.SjEndTime.Date <= select_end_time.Date)
                    .ToListAsync();
                    decimal total = 0;
                    foreach (var nrWorkOrder in nrWorkOrders)
                    {
                        total += (nrWorkOrder.SjEndTime - nrWorkOrder.NoticeRepair.TroubleTime).TotalHours.ToDecimal();
                    }
                    data.Add(select_begin_time.ToString("yyyy-MM-dd"), total);
                }
            }

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 报表管理-维修工单-设备维修工时消耗统计
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="rt"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostShebeiweixiugongshixiaohaotongji([FromForm] long eid, [FromForm] string rt)
        {
            Dictionary<string, string> data = new();
            // 计算时间范围段
            DateTime begintime = DateTime.Now;
            DateTime endtime = DateTime.Now;
            DateTime ct = DateTime.Now;
            if (rt.Equals("本周"))
            {
                begintime = ct.AddDays(1 - (ct.DayOfWeek == DayOfWeek.Sunday ? 7 : int.Parse(ct.DayOfWeek.ToString("d")))); // 本周一
                endtime = begintime.AddDays(6); // 本周日
                for (int i = 0; i < 7; i++)
                {
                    // 本周当前时间
                    DateTime select_time = begintime.AddDays(i);
                    // 维修工时
                    string weixiu_manhour = await db.Queryable<NrWorkOrder>().Where(wo => wo.Eid == eid).Where(wo => wo.Status == "已完成").Where(wo => wo.SjEndTime.Date == select_time.Date).Select(wo => SqlFunc.AggregateSum(wo.SjManHour)).SingleAsync();
                    data.Add(select_time.ToString("yyyy-MM-dd"), weixiu_manhour);
                }
            }

            if (rt.Equals("本月"))
            {
                begintime = ct.AddDays(1 - ct.Day);  //本月月初
                endtime = begintime.AddMonths(1).AddDays(-1);  //本月月末
                for (int i = 0; i < endtime.Day; i++)
                {
                    // 本月当前时间
                    DateTime select_time = begintime.AddDays(i);
                    // 维修工时
                    string weixiu_manhour = await db.Queryable<NrWorkOrder>().Where(wo => wo.Eid == eid).Where(wo => wo.Status == "已完成").Where(wo => wo.SjEndTime.Date == select_time.Date).Select(wo => SqlFunc.AggregateSum(wo.SjManHour)).SingleAsync();
                    data.Add(select_time.ToString("yyyy-MM-dd"), weixiu_manhour);
                }
            }

            if (rt.Equals("本年"))
            {
                begintime = new DateTime(ct.Year, 1, 1);  //本年年初
                for (int i = 0; i < 12; i++)
                {
                    // 本月开始时间和结束时间
                    DateTime select_begin_time = begintime.AddMonths(i);
                    DateTime select_end_time = begintime.AddMonths(i + 1);
                    // 维修工时
                    string weixiu_manhour = await db.Queryable<NrWorkOrder>().Where(wo => wo.Eid == eid).Where(wo => wo.Status == "已完成").Where(wo => wo.SjEndTime.Date >= select_begin_time.Date && wo.SjEndTime.Date < select_end_time.Date).Select(wo => SqlFunc.AggregateSum(wo.SjManHour)).SingleAsync();
                    data.Add(select_begin_time.ToString("yyyy-MM-dd"), weixiu_manhour);
                }
            }

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
    }
}
